import { Fragment, useEffect, useState } from 'react';
import { NavLink, useNavigate } from 'react-router-dom';
import { Card, Row, Col, Space, PageHeader, List, Button } from 'antd';
import { BarChartOutlined } from '@ant-design/icons';
import { http } from '@/utils/http';
import { HeartIcon } from '@/utils/HeartIcon';
import './index.scss';

export default function News() {
  const navigate = useNavigate()
  const [categoryList, setCategoryList] = useState([])  // 新闻分类列表

  // 获取新闻列表
  const getNewsList = async () => {
    const { data } = await http.get('/news?publishState=2&_expand=category&_sort=star&_order=desc')

    // 数据处理
    const formatData = data.map(item => item.category.title)
    // console.log(data)

    let De_WeightDataList = [];  // 暂存新闻分类列表
    formatData.forEach(item => {
      if (De_WeightDataList.indexOf(item) === -1) {
        De_WeightDataList.unshift(item)
      }
    });
    // console.log(De_WeightDataList)

    let renderList = [];  // 暂存新闻列表
    for (let i = 0; i < De_WeightDataList.length; i++) {
      const dataMap = data.map(item => {
        if (item.category.title === De_WeightDataList[i]) {
          return item
        }
        return null;
      })
      const formatDataMap = dataMap.filter(item => item !== null)
      renderList.push([
        De_WeightDataList[i],
        formatDataMap
      ])
    }
    // console.log(renderList)

    setCategoryList(renderList)
  }

  useEffect(() => {
    getNewsList()
  }, [])

  // 点击返回按钮的回调
  const clickBack = e => {
    e.target.style.cursor = 'wait'
    setTimeout(() => {
      window.history.back()
    }, 300)
  }

  // 登录后台按钮的回调
  const login = e => {
    e.target.style.cursor = 'wait'
    setTimeout(() => {
      navigate('/login')
    }, 100)
  }

  return (
    <Fragment>
      <div className='news-body' style={{
        width: '100%',
        minWidth: '850px',
        minHeight: '100%',
        backgroundColor: 'aliceblue',
        display: 'flex',
        flexWrap: 'wrap',
        alignContent: 'center',
        justifyContent: 'center',
        overflow: 'auto'
      }}
      >
        <Button ghost onClick={e => clickBack(e)} style={{
          position: 'absolute',
          top: '30px',
          left: '36px',
          backgroundColor: '#EFEFEF',
          border: '1px solid gray',
          color: '#1190FA',
          fontWeight: 'bold',
        }}>goBack</Button>
        <Button ghost onClick={e => login(e)} style={{
          position: 'absolute',
          top: '30px',
          right: '36px',
          backgroundColor: '#EFEFEF',
          border: '1px solid gray',
          color: '#1190FA',
          fontWeight: 'bold',
        }}>Login to backstage</Button>
        <PageHeader title={
          <div className='page-header-img' />
        } subTitle="新闻发布系统前台" />
        <Row gutter={[36, 48]}>
          {
            categoryList.map((item, index) => {
              return (
                <Col span={8} key={index}>
                  <Card style={{ height: '255px' }} hoverable title={
                    <Fragment>
                      <Space>
                        {item[0]}
                        <BarChartOutlined style={{ color: '#FF2020', fontSize: '17px' }} />
                      </Space>
                    </Fragment>
                  }>
                    <List
                      height="100%"
                      dataSource={item[1]}
                      pagination={{
                        pageSize: 2
                      }}
                      renderItem={({ title, id, star }) => (
                        <List.Item>
                          <NavLink to={`/detail/${id}`}>{title}</NavLink>
                          <div>
                            <Space>
                              <span style={{ color: '#8C8C8C' }}>{star}</span>
                              <HeartIcon style={{ color: 'hotpink' }} />
                            </Space>
                          </div>
                        </List.Item>
                      )}
                    />
                  </Card>
                </Col>
              )
            })
          }
        </Row>
      </div>
    </Fragment>
  )
}